﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocialPlatformSDK.Model;
using SocialPlatformSDK.Util;

namespace SocialPlatformSDK
{

    public class TencentCodeToken : CodeToken
    {
        /// <summary>
        ///  用来换取accesstoken的授权码，有效期为10分钟
        /// </summary>
      

        public  string Openid { get; set; }

        /// <summary>
        /// 与openid对应的用户key，是验证openid身份的验证密钥
        /// </summary>
        public string Openkey { get; set; }

        public override void LoadToken(string content)
        {
            var result = OAuthHelper.GetQueryParameters(content);

            // 通过content, 初始化 Key 和 Secret
            if (result.ContainsKey("code"))
            {
                this.Code = result["code"];
            }
            if (result.ContainsKey("openid"))
            {
                this.Openid = result["openid"];
            }
            if (result.ContainsKey("openkey"))
            {
                this.Openkey = result["openkey"];
            }
        }
    }


    public class TencentAccessToken : AccessToken
    {

        public override void LoadToken(string content)
        {
            var result = OAuthHelper.GetQueryParameters(content);
            this.AccesssToken = result["access_token"];
            this.RefleshToken = result["refresh_token"];
            this.ExpriesIn = result["expires_in"];

        }
    }

        internal static class OAuthHelper
    {
        /// <summary>
        /// 将服务器返回的结果转换为参数列表.
        /// </summary>
        /// <param name="response">服务器返回的结果./param>
        /// <returns>返回参数列表.</returns>
            internal static Dictionary<string, string> GetQueryParameters(string response)
            {
                Dictionary<string, string> nameValueCollection = new Dictionary<string, string>();
                string[] items = response.Split('&');

                foreach (string item in items)
                {
                    if (item.Contains("="))
                    {
                        string[] nameValue = item.Split('=');
                        if (nameValue[0].Contains("?"))
                            nameValue[0] = nameValue[0].Replace("?", "");
                        nameValueCollection.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
                    }
                }
                return nameValueCollection;
            }
    }

      
}
